import copy
import time

import pygame
import sys
import random
import os
from game.entity.block import Block
from game.utils.utils import Utils

pygame.init()

# 移动步长
step = 30
width_screen = 20
height_screen = 15
# 设置窗口大小和标题
screen = pygame.display.set_mode((step*width_screen, step*height_screen))
pygame.display.set_caption("贪吃蛇小游戏")
# 背景图片
background_image_path = "img_sky.png"
# 方块图片
block_img_path = "img_block.png"

# 设置背景颜色为淡蓝色
bg_color = (155,196,226)
red = (255,0,0)
# 方块集合
block_list = []
# 排除数字结合
exclude_nums = [1,2]



block_0 = Block(100,100,50,50,(255,255,255))
block_0.setText(pygame,"1")
block_list.append(block_0)
# 上一次 末尾位置
block_last = Block(0,0,50,50,(255,255,255))
# 运行状态
running = True
# 文件路径
main_dir = os.path.split(os.path.abspath(__file__))[0]


# 移动list所有方块
def moveAll(stepx,stepy,block_list,keyEvent):
    global block_last
    print(time_start)
    block_last = copy.copy(block_list[len(block_list)-1])
    block_start = block_list[0]
    block_end = copy.copy(block_list.pop())
    new_x = 0
    new_y = 0
    if keyEvent == "left":
        new_x = -1
    if keyEvent == "right":
        new_x = 1
    if keyEvent == "up":
        new_y = -1
    if keyEvent == "down":
        new_y = 1
    block_end.x = block_start.x + new_x * block_start.width
    block_end.y = block_start.y + new_y * block_start.height
    block_list.insert(0,block_end)
    # block_end.move(stepx,stepy)
    # for block in block_list:
    #     block.move(stepx,stepy)

# 绘制所有方块
def drawAll(block_list,re):
    # block_list.text进行排序处理
    text_List = []
    for block in block_list:
        text_List.extend([ord(char) for char in block.text])
    text_List.sort();
    if re == -1:
        block_list.reverse()
        text_List.reverse()
    for index,block in enumerate(block_list):
        block.setText(pygame,str(chr(text_List[index])))
        block.draw(screen,pygame)

def restart_game():
    global running,block_list,exclude_nums,block_new
    block_list = []
    exclude_nums = []
    block_0 = Block(100,200,50,50,(255,255,255))
    block_0.setText(pygame,"1")
    block_new = Block(10,10,50,50,(255,255,255))
    block_new.setText(pygame,"2")
    block_list.append(block_0)
    return block_list

def game_loop():
    global running,block_list,exclude_nums,block_new,time_start,main_dir
    # 开始时间
    time_start = time.time()
    bg_music = Utils.load_sound("house_lo.wav",main_dir)
    # bg_music.play(-1)
    if len(block_list)==1:
        block_new = Block(0,0,50,50,(255,255,255))
        block_new.setText(pygame,"2")
    # 游戏循环
    while running:
        # 处理游戏事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                # 原地掉头
                drawAll(block_list,-1)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print("鼠标单机")
                if event.button == 1:
                    print("鼠标单机重新开始")
                    block_list = restart_game()
            # 更新小蜜蜂的位置
            keys = pygame.key.get_pressed()
            if keys[pygame.K_LEFT]:
                if block_list[0].x -step >=0:
                    moveAll(-step,0,block_list,"left")
            if keys[pygame.K_RIGHT]:
                if block_list[0].x +step < screen.get_width():
                    moveAll(step,0,block_list,"right")
            if keys[pygame.K_UP]:
                if block_list[0].y -step >=0:
                    moveAll(0,-step,block_list,"up")
            if keys[pygame.K_DOWN]:
                if block_list[0].y + step < screen.get_height():
                    moveAll(0,step,block_list,"down")


        # 碰撞处理
        if pygame.Rect(block_list[0].show()).colliderect(pygame.Rect(block_new.show())):
            file = "boom.wav"
            boom = Utils.load_sound(file,main_dir)
            boom.play()
            print("碰到一起了")
            block_temp = copy.copy(block_new)
            # block_temp.x = block_list[len(block_list)-1].x + block_new.width
            # block_temp.y = block_list[len(block_list)-1].y
            block_temp.x = block_last.x
            block_temp.y = block_last.y
            block_temp.image = None
            # block_temp.color = (255,255,255)
            block_list.append(block_temp)
            # block_new.x = random.randint(0, screen.get_width() - block_new.width)
            # block_new.y = random.randint(0, screen.get_height() - block_new.width)
            block_new.x = abs(step * (random.randint(1, 20-1)))
            block_new.y = abs(step * (random.randint(1, 15-1)))
            # while block_new.x>=width_screen:
            #     block_new.x = step * (random.randint(0, 20)-1)
            # while block_new.y>=height_screen:
            #     block_new.y = step * (random.randint(0, 15)-1)
            block_new.x = abs(block_new.x)
            block_new.y = abs(block_new.y)
            block_new.color = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
            #获取随机数字+字母
            random_num = Utils.getRandom(exclude_nums)
            block_new.setText(pygame,str(chr(random_num)))

        # 绘制背景
        background_image = Utils.load_image(background_image_path,screen.get_size(),main_dir)
        background = pygame.Surface(screen.get_size())
        for x in range(0,screen.get_width(),background_image.get_width()):
            background.blit(background_image,(x,0))
            for y in range(0,screen.get_height(),background_image.get_height()):
                background.blit(background_image,(x,y))
        #设置背景颜色
        screen.fill(bg_color)
        # 设置背景图片
        screen.blit(background,(0,0))
        # 绘制方块
        drawAll(block_list,1)
        # 方块图片
        block_img = Utils.load_image(block_img_path,block_new.size(),main_dir)
        block_new.setImage(block_img)
        block_new.draw(screen,pygame)


        # print(block_last.show())
        # print(exclude_nums)
        # screen.blit(text_surface, text_rect)
        # 更新屏幕显示
        pygame.display.update()
        time_now = time.time()
        if time_now-time_start> 1:
            time_start = time_now
            block_new.color = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
            block_new.draw(screen,pygame)
            pygame.display.update()



    # 退出游戏
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    game_loop()
